//
//  CrossModel.m
//  糗事百科
//
//  Created by 奚超明 on 16/6/1.
//  Copyright © 2016年 奚超明. All rights reserved.
//

#import "CrossModel.h"
#import "CrossUserModel.h"
#import "ImageModel.h"

@implementation CrossModel

+ (instancetype)crossWithDic:(NSDictionary *)dic
{
    CrossModel *model = [[CrossModel alloc] init];
    [model setValuesForKeysWithDictionary:dic];
    model.up = dic[@"votes"][@"up"];
    model.user = [CrossUserModel crossUserWithDic:dic[@"user"]];
    if (![dic[@"image_size"] isKindOfClass:[NSNull class]]) {
        model.image_size = [ImageModel imageWithDic:dic[@"image_size"]];
    }
    if (![dic[@"image"] isKindOfClass:[NSNull class]]) {
        model.image = [self iconUrlStringWithImageString:dic[@"image"]];
    }
    return model;
}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{
    if ([key isEqualToString:@"id"]) {
        self.ID = [value stringValue];
    }
}

#pragma mark - 图像的拼接
+ (NSString *)iconUrlStringWithImageString:(NSString *)imageString
{
    NSString *substring1 = [imageString substringFromIndex:3];
    NSString *subString2 = [substring1 substringToIndex:5];
    NSString *subString3 = [substring1 substringToIndex:9];
    NSString *urlstring = [NSString stringWithFormat:@"%@/%@/medium/%@",subString2,subString3, imageString];
    NSString *iconUrlString = [@"http://pic.qiushibaike.com/system/pictures/" stringByAppendingString:urlstring];
    return iconUrlString;
}

- (CGFloat)cellHeight
{
    if (!_cellHeight) {
        // 文字最大尺寸
        CGSize maxSize = CGSizeMake([UIScreen mainScreen].bounds.size.width - 2 * kMargin, MAXFLOAT);
        // 计算文字高度
        CGFloat textH = [self.content boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil].size.height;
        
        // 内容高度
        _cellHeight = kIconImageHeight + textH + 2 * kMargin + kBottomHeight;
        
        // 如果有图片
        if (self.image) {
            // 图片高度
            _cellHeight = kMargin + self.image_size.height + _cellHeight;
        }
    }
    return _cellHeight;
}

@end
